/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */

import React, { useRef, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import Config from '@/config';
import styles from './index.module.less';
import { useAuth } from '@/app/auth';

const lines: (string | React.ReactNode)[] = [];

function AntechamberConversation(props: React.HTMLAttributes<HTMLDivElement>) {
  const { className, ...rest } = props;
  const msgHistory = useSelector((state: RootState) => state.room.msgHistory);
  const containerRef = useRef<HTMLDivElement>(null);
  const { user } = useAuth();

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.scrollTop = container.scrollHeight - container.clientHeight;
    }
  }, [msgHistory.length]);



  return (
    <div ref={containerRef} className={`${styles.conversation} ${className}`} {...rest}>
      {lines.map((line) => line)}
      {msgHistory.length === 0 ? <div className={styles.aiReadying}>点击开始对话吧～ </div> : ''}

      {msgHistory?.map(({ value, user: messageUser }, index) => {
        const isUserMsg = messageUser === `${user?.userId || ''}_${user?.username || ''}`;
        const isRobotMsg = messageUser === Config.BotName;
        if (!isUserMsg && !isRobotMsg) {
          return '';
        }
        return (
          <div className={`${styles.sentence} ${isUserMsg ? styles.user : styles.robot}`} key={`msg-${index}`}>
            <div className={styles.content}>
              {value}
            </div>
          </div>
        );
      })}
    </div>
  );
}

export default AntechamberConversation;
